package net.sk.china.city.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.support.ExcelTypeEnum;
import net.sk.china.city.config.component.ExcelScanListener;
import net.sk.china.city.constant.ImportMode;
import net.sk.china.city.domain.dto.excel.ReadUser;
import net.sk.china.city.mapper.ArTeamMapper;
import net.sk.china.city.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@Transactional
@Component
public class ExcelUtil {

    private static IUserService userService;
    private static ArTeamMapper teamMapper;

    @Autowired
    public ExcelUtil(IUserService userService, ArTeamMapper teamMapper) {
        ExcelUtil.userService = userService;
        ExcelUtil.teamMapper = teamMapper;
    }

    /**
     * 读取excel数据，并存入数据库
     *
     * @param file
     * @throws IOException
     */
    public static void importUser(MultipartFile file, ImportMode importMode) throws IOException {
        // 构建 ExcelReader 对象，从第二行开始
        ExcelReader excelReader = EasyExcel.read(file.getInputStream(),
                        ReadUser.class,
                        new ExcelScanListener(teamMapper, userService, importMode))
                .excelType(ExcelTypeEnum.XLSX)
                .headRowNumber(1)
                .build();
        // 读取 Excel 表格中的数据
        excelReader.readAll();
        // 关闭 ExcelReader
        excelReader.finish();
    }

}
